<?php
/**
 * Description of annonce
 *
 * @author Gmax
 */
class modules_immobilier_annonce extends modele_publication {
    public $type = 'annonce';
    
    private $_type_logement_id;
    private $_type_logement = '';
    private $_prix = 0;
    private $_vendeur = '';
    private $_phone1 = '';
    private $_phone2 = '';
    private $_mail = '';
    private $_adresse_id = 0;
    private $_adresse = null;
    
    private $_nbr_pieces = 1;
    private $_surface = 0;
    private $_taxe_fonciere = 0;
    private $_taxe_habitation = 0;
    private $_charges_copro = 0;
    private $_dpe;
    private $_ges;
    
    private $_indiceDpe = array('50'=>'a','90'=>'b','150'=>'c','230'=>'d','330'=>'e','450'=>'f','451'=>'g');
    private $_indiceGes = array('5'=>'a','10'=>'b','20'=>'c','35'=>'d','55'=>'e','80'=>'f','81'=>'g');
    
    private $_items = array();
    
    private $_statut_vente = 0;
    
    public function __construct($id = null) {
        parent::__construct($id);
        if($this->getId()>0){
            $this->_getDatasAnnonce();
            $this->_getItemsAnnonce();
        }
    }
    
    private function _getDatasAnnonce(){
        $sqlDatas = 'SELECT a.*, ';
        $sqlDatas .= 'tl.nom as type_logement ';
        $sqlDatas .= 'FROM '.PWE::getPrefixBdd().'annonce_immobiliere AS a ';
        $sqlDatas .= 'LEFT JOIN '.PWE::getPrefixBdd().'type_logement AS tl ON tl.id = a.type_logement_id ';
        $sqlDatas .= 'WHERE a.publication_id = '.$this->getId();

        $datas = $this->_getOneResult($sqlDatas);
        if($datas){
            $this->_vendeur = $datas['vendeur'];
            $this->_phone1 = $datas['phone1'];
            $this->_phone2 = $datas['phone2'];
            $this->_mail = $datas['mail'];
            $this->_adresse_id = $datas['adresse_id'];
            $this->_adresse = new modele_adresse($this->_adresse_id);
            
            $this->_statut_vente = $datas['statut_vente'];
            $this->_prix = $datas['prix'];
            $this->_type_logement_id = $datas['type_logement_id'];
            $this->_type_logement = $datas['type_logement'];
            $this->_nbr_pieces = $datas['nbr_pieces'];
            $this->_surface = $datas['surface'];
            $this->_taxe_fonciere = $datas['taxe_fonciere'];
            $this->_taxe_habitation = $datas['taxe_habitation'];
            $this->_charges_copro = $datas['charges_copro'];
            $this->_dpe = $datas['dpe'];
            $this->_ges = $datas['ges'];
        }
    }
    
    private function _getItemsAnnonce(){
        $sqlItem = 'SELECT i.*, ';
        $sqlItem .= 'ti.nom as type_item ';
        $sqlItem .= 'FROM '.PWE::getPrefixBdd().'item_annonce_immobiliere AS i ';
        $sqlItem .= 'LEFT JOIN '.PWE::getPrefixBdd().'type_item AS ti ON ti.id = i.type_item_id ';
        $sqlItem .= 'WHERE i.annonce_id = '.$this->getId().' ';
        $sqlItem .= 'ORDER BY i.ordre';
        
        $results = bdd_sql::doSql($sqlItem);
        if($results['count']>0){
            $this->_items = array();
            foreach($results['results'] as $item){
                $this->_items[] = array(
                    'id'=>$item['id'],
                    'type_item_id'=>$item['type_item_id'],
                    'type'=>$item['type_item'],
                    'title'=>$this->outputFormat($item['title']),
                    'value'=>$this->outputFormat($item['value']),
                    'ordre'=>$item['ordre']
                );
            }
        }
    }
    
    ////////////////////////// le vendeur
    
    /**
     * renvoi les nom prénom du vendeur
     * @param boolean $input default false
     * @return string
     */
    public function getVendeur($input=false){
        if($input){
            return $this->inputFormat($this->_vendeur);
        }else{
            return $this->outputFormat($this->_vendeur);
        }
    }
    /**
     * renvoi l'adresse_id du logement
     * @return int
     */
    public function getAdresseId(){
        return $this->_adresse_id;
    }
    /**
     * renvoi l'objet adresse du logement
     * @return \modele_adresse|null
     */
    public function getAdresse(){
        if($this->_adresse === null && $this->getAdresseId()>0){
            $this->_adresse = new modele_adresse($this->getAdresseId());
        }
        return $this->_adresse;
    }
    /**
     * renvoi le nom de la ville
     * @param boolean $input
     * @return string
     */
    public function getVille($input=false){
        if($this->getAdresse()!==null){
            return $this->getAdresse()->getVille($input);
        }else{
            return '';
        }
    }
    /**
     * renvoi le téléphone 1 contact du vendeur
     * @return string
     */
    public function getPhone1(){
        return $this->_phone1;
    }
    /**
     * renvoi le téléphone 2 contact du vendeur
     * @return string
     */
    public function getPhone2(){
        return $this->_phone2;
    }
    /**
     * renvoi le mail contact du vendeur
     * @return string
     */
    public function getMail(){
        return $this->_mail;
    }
    
    ///////////////////////////////////// le logement
    /**
     * 
     * @return int
     */
    public function getStatutVente(){
        return $this->_statut_vente;
    }
    /**
     * indique si le bien est vendu
     * @return boolean
     */
    public function isVendu(){
        return ($this->getStatutVente()==0)?false:true;
    }
    
    /**
     * mettre le logmenet en vente
     */
    public function setEnVente(){
        $this->_statut_vente = 0;
        $sqlQuery = 'UPDATE '.PWE::getPrefixBdd().'annonce_immobiliere SET statut_vente='.$this->getStatutVente(). ' WHERE publication_id='.$this->getId().' LIMIT 1';
        bdd_sql::doSql($sqlQuery,false);
    }
    /**
     * mettre le logmenet comme vendu
     */
    public function setVendu(){
        $this->_statut_vente = 1;
        $sqlQuery = 'UPDATE '.PWE::getPrefixBdd().'annonce_immobiliere SET statut_vente='.$this->getStatutVente(). ' WHERE publication_id='.$this->getId().' LIMIT 1';
        bdd_sql::doSql($sqlQuery,false);
    }
    /**
     * renvoi le prix du bien
     * @return string
     */
    public function getPrix(){
        return $this->_prix;
    }
    /**
     * renvoi le type_logement_id
     * @return int
     */
    public function getTypeLogementId(){
        return $this->_type_logement_id;
    }
    /**
     * renvoi le type de logement 
     * @param boolean $input
     * @return string maison|appartement
     */
    public function getTypeLogement($input=false){
        if($input){
            return $this->inputFormat($this->_type_logement);
        }else{
            return $this->outputFormat($this->_type_logement);
        }
    }
    /**
     * renvoi le nombre de pièces du logement
     * @return int
     */
    public function getNombrePieces(){
        return $this->_nbr_pieces+0;
    }
    /**
     * renvoi la surface total du logement
     * @return string
     */
    public function getSurface(){
        return $this->_surface;
    }
    /**
     * renvoi le montant de la taxe foncière
     * @return number
     */
    public function getTaxeFonciere(){
        return $this->_taxe_fonciere;
    }
    /**
     * renvoi le montant de la taxe d'habitation
     * @return number
     */
    public function getTaxeHabitation(){
        return $this->_taxe_habitation;
    }
    /**
     * renvoi le montant des charges de co-propriété
     * @return number
     */
    public function getChargesCopropriete(){
        return $this->_charges_copro;
    }
    /**
     * renvoi la lettre dpe
     * @return srting
     */
    public function getDpe(){
        return $this->_dpe;
    }
    /**
     * renvoi la lettre de l'indice DPE
     * @return string
     */
    public function getIndiceDpe(){
        $value = $this->getDpe();
        $retour = '';
        if($value!=''&&$value>=0){
            foreach ($this->_indiceDpe as $v=>$l){
                $retour = $l;
                if($v>$value){
                    break;
                }
            }        
        }
        
        return $retour;
    }
    /**
     * renvoi la lettre ges
     * @return srting
     */
    public function getGes(){
        return $this->_ges;
    }
    /**
     * renvoi la lettre de l'indice GES
     * @return string
     */
    public function getIndiceGes(){
        $value = $this->getGes();
        $retour = '';
        if($value!=''&&$value>=0){
            foreach ($this->_indiceGes as $v=>$l){
                $retour = $l;
                if($v>$value){
                    break;
                }
            }        
        }
        
        return $retour;
    }
    /**
     * renvoi le nombre total de chambres
     * @return int
     */
    public function getNombreChambre(){
        return count($this->getItemByType('chambre'));
    }
        
    /**
     * retourne la liste des items
     * @return array id,type,type_item_id,title,value,ordre
     */
    public function getItems(){
        return $this->_items;
    }
    
    /**
     * retourne la liste des items par type
     * @param string $type
     * @return array id,type,type_item_id,title,value,ordre
     */
    public function getItemByType($type){
        $retour = array();
        foreach($this->getItems() as $item){
            if($item['type']===$type){
                $retour[] = $item;
            }
        }
        
        return $retour;
    }
    
    /**
     * retourne la liste des items par son identifiant
     * @param int $id
     * @return array id,type,type_item_id,title,value,ordre
     */
    public function getItemById($id){
        $retour = null;
        foreach($this->getItems() as $item){
            if($item['id']===$id){
                $retour = $item;
            }
        }
        return $retour;
    }
    
    /**
     * retourne l'item selon son ordre
     * @param int $id
     * @return array id,type,type_item_id,title,value,ordre
     */
    public function getItemByOrder($order){
        $retour = null;
        foreach($this->getItems() as $item){
            if($item['ordre']==$order){
                $retour = $item;
            }
        }
        return $retour;
    }
    /**
     * retourne l'item suivant selon l'ordre
     * @param int $order
     * @return array
     */
    public function getNextOrderItem($order){
        $retour = null;
        foreach($this->getItems() as $item){
            if($item['ordre']>$order){
                $retour = $item;
                break;
            }
        }
        return $retour;
    }
    
    /**
     * retourne l'item suivant selon l'ordre
     * @param int $order
     * @return array
     */
    public function getPrevOrderItem($order){
        $retour = null;
        foreach($this->getItems() as $item){
            if($item['ordre']<$order){
                $retour = $item;
            }else{
                break;
            }
        }
        return $retour;
    }
    
    public function addItem($datas){
        $queryMax = 'SELECT MAX(ordre) as max FROM '.PWE::getPrefixBdd().'item_annonce_immobiliere WHERE annonce_id='.$this->getId();
        $max = $this->_getOneResult($queryMax);
        if($max &&$max['max']!=null){
            $order = $max['max']+1;
        }else{
            $order = 1;
        }
        
        
        $sqlQuery = 'INSERT INTO '.PWE::getPrefixBdd().'item_annonce_immobiliere '
            . '(annonce_id,title,type_item_id,value,ordre) '
            . 'VALUES ('
            . $this->getId()
            . ',"'.$this->inputFormat($datas['title']).'"'
            . ','.$datas['type_item_id']
            . ',"'.$this->inputFormat($datas['value']).'"'
            . ','.$order
            . ')';
        bdd_sql::doSql($sqlQuery);
        
        $this->_getItemsAnnonce();
    }
    public function updateItem($datas){
        $sqlQuery = 'UPDATE '.PWE::getPrefixBdd().'item_annonce_immobiliere '
            . 'SET '
            . 'title="'.$this->inputFormat($datas['title']).'"'
            . ',type_item_id='.$datas['type_item_id']
            . ',value="'.$this->inputFormat($datas['value']).'"'
            . ' WHERE id='.$datas['id'].' LIMIT 1';
        bdd_sql::doSql($sqlQuery);
    }
    public function removeItem($id){
        $sqlDelete = 'DELETE FROM '.PWE::getPrefixBdd().'item_annonce_immobiliere WHERE id='.$id;
        bdd_sql::doSql($sqlDelete);
    }
    
    public function upItem($id){
        $item = $this->getItemById($id);
        if($item!==null){
            $currentOrder = $item['ordre'];
            $upItem = $this->getPrevOrderItem($currentOrder);
            if($upItem!==null){
                $sql = 'UPDATE '.PWE::getPrefixBdd().'item_annonce_immobiliere '
                    . 'SET ordre='.($currentOrder)
                    . ' WHERE id='.$upItem['id'].' LIMIT 1';
                bdd_sql::doSql($sql);
            
                $sql = 'UPDATE '.PWE::getPrefixBdd().'item_annonce_immobiliere '
                    . 'SET ordre='.($upItem['ordre'])
                    . ' WHERE id='.$item['id'].' LIMIT 1';
                bdd_sql::doSql($sql);
                
                $this->_getItemsAnnonce();
            }
        }
    }

    public function downItem($id){
        $item = $this->getItemById($id);
        if($item!==null){
            $currentOrder = $item['ordre'];
            $downItem = $this->getNextOrderItem($currentOrder);
            if($downItem!==null){
                $sql = 'UPDATE '.PWE::getPrefixBdd().'item_annonce_immobiliere '
                    . 'SET ordre='.($currentOrder)
                    . ' WHERE id='.$downItem['id'].' LIMIT 1';
                bdd_sql::doSql($sql);
            
                $sql = 'UPDATE '.PWE::getPrefixBdd().'item_annonce_immobiliere '
                    . 'SET ordre='.($downItem['ordre'])
                    . ' WHERE id='.$item['id'].' LIMIT 1';
                echo $sql;
                bdd_sql::doSql($sql);

                $this->_getItemsAnnonce();
            }
        }
    }

    public function getDatas($input = false) {
        $datas = parent::getDatas($input);
        $datas['statut_vente'] = $this->getStatutVente();
        $datas['type_logement'] = $this->getTypeLogement();
        $datas['type_logement_id'] = $this->getTypeLogementId();
        $datas['items'] = $this->getItems();
        $datas['vendeur'] = $this->getVendeur();
        $datas['adresse_id'] = $this->getAdresseId();
        $datas['adresse'] = ($this->getAdresse()!=null)?$this->getAdresse()->getDatas($input):null;
        $datas['phone1'] = $this->getPhone1();
        $datas['phone2'] = $this->getPhone2();
        $datas['mail'] = $this->getMail();
        
        $datas['prix'] = $this->getPrix();
        $datas['nbr_pieces'] = $this->getNombrePieces();
        $datas['surface'] = $this->getSurface();
        $datas['taxe_fonciere'] = $this->getTaxeFonciere();
        $datas['taxe_habitation'] = $this->getTaxeHabitation();
        $datas['charges_copro'] = $this->getChargesCopropriete();
        $datas['dpe'] = $this->getDpe();
        $datas['ges'] = $this->getGes();
        
        return $datas;
    }
    
    public function setDatas($datas) {
        parent::setDatas($datas);
        
        foreach($datas as $k=>$v){
            if(substr($k, 0, 1) !== '_') $k = '_'.$k;
            if($k != '_id' && property_exists('modules_immobilier_annonce',$k)){
                $this->$k = $v;
            }
        }
        
        // adresse
        if($this->getAdresse()!=null){
            $adresse = $this->getAdresse();
        }else{
            $adresse = new modele_adresse();
        }
        
        $adresse->setDatas($datas);
        $this->_adresse = $adresse;
        
        return true;
    }
    
    public function save() {
        $retour = parent::save();
        if($this->getId()>0){
            // adresse 
            if($this->getAdresse() !== null && $this->getAdresseId()>0){
                $retourAdresse = $this->getAdresse()->update();
            }elseif($this->getAdresse() !== null){
                $retourAdresse = $this->getAdresse()->save();
            }
            if($retourAdresse['success']){
                $this->_adresse_id = $this->getAdresse()->getId();
            }
            
            $sqlQuery = 'INSERT INTO '.PWE::getPrefixBdd().'annonce_immobiliere ';
            $sqlQuery .= '(publication_id,prix,vendeur,adresse_id,phone1,phone2,mail,nbr_pieces,surface,taxe_fonciere,taxe_habitation,charges_copro,dpe,ges,type_logement_id,statut_vente) ';
            $sqlQuery .= 'VALUES ('.$this->getId()
                . ',"'.$this->getPrix().'"'
                . ',"'.$this->getVendeur(true).'",';
            $sqlQuery .=  ($this->getAdresseId()>0)?$this->getAdresseId():'NULL';
            $sqlQuery .=  ',"'.$this->getPhone1().'"'
                . ',"'.$this->getPhone2().'"'
                . ',"'.$this->getMail().'"'
                . ','.$this->getNombrePieces()
                . ',"'.$this->getSurface().'"'
                . ',"'.$this->getTaxeFonciere().'"'
                . ',"'.$this->getTaxeHabitation().'"'
                . ',"'.$this->getChargesCopropriete().'"'
                . ',"'.$this->getDpe().'"'
                . ',"'.$this->getGes().'"'
                . ','.$this->getTypeLogementId()
                . ','.$this->getStatutVente()
                . ')';
            bdd_sql::doSql($sqlQuery,false);
        }
        return $retour;
    }
    
    public function update() {
        $retour = parent::update();
        
        // adresse 
        if($this->getAdresse() !== null && $this->getAdresseId()>0){
            $retourAdresse = $this->getAdresse()->update();
        }elseif($this->getAdresse() !== null){
            $retourAdresse = $this->getAdresse()->save();
        }
        if($retourAdresse['success']){
            $this->_adresse_id = $this->getAdresse()->getId();
        }
        
        $sqlQuery = 'UPDATE '.PWE::getPrefixBdd().'annonce_immobiliere SET '
            . 'prix="'.$this->getPrix().'"'
            . ',vendeur="'.$this->getVendeur(true).'"';
        $sqlQuery .= ($this->getAdresseId()>0)?',adresse_id='.$this->getAdresseId():'';
        $sqlQuery .= ',phone1="'.$this->getPhone1().'"'
            . ',phone2="'.$this->getPhone2().'"'
            . ',mail="'.$this->getMail().'"'
            . ',nbr_pieces='.$this->getNombrePieces()
            . ',surface="'.$this->getSurface().'"'
            . ',taxe_fonciere="'.$this->getTaxeFonciere().'"'
            . ',taxe_habitation="'.$this->getTaxeHabitation().'"'
            . ',charges_copro="'.$this->getChargesCopropriete().'"'
            . ',dpe="'.$this->getDpe().'"'
            . ',ges="'.$this->getGes().'"'
            . ',type_logement_id='.$this->getTypeLogementId()
            . ',statut_vente='.$this->getStatutVente()
            . ' WHERE publication_id='.$this->getId().' LIMIT 1';
        bdd_sql::doSql($sqlQuery,false);
        return $retour;
    }
    
    public function delete() {
        $this->getAdresse()->delete();
        $sqlDelete = 'DELETE FROM '.PWE::getPrefixBdd().'annonce_immobiliere WHERE publication_id='.$this->getId();
        bdd_sql::doSql($sqlDelete,false);
        return parent::delete();
    }
    
    // méthodes statiques
    /**
     * renvoi la liste des annonces
     * @param int $start
     * @param int $limit
     * @param boolean $public default false, si true -> uniquement les biens en ligne
     * @param boolean $dispo default false, si true -> uniquement les biens non vendus
     * @return \modules_immobilier_annonce
     */
    public static function getListe($start=0,$limit=0,$public=false,$dispo=false){
        $sqlQuery = 'SELECT a.publication_id AS id FROM '.PWE::getPrefixBdd().'annonce_immobiliere AS a';
        $sqlQuery .= ' LEFT JOIN '.self::getTable().' AS p on p.id=a.publication_id';
        if($dispo||$public){
            $sqlQuery .= ' WHERE';
            if($public){
                $sqlQuery .= ' p.statut_id=2';
                if($dispo){
                    $sqlQuery .= ' AND a.statut_vente=0';
                }
            }else{
                $sqlQuery .= ' a.statut_vente=0';
            }
        }
        
        $sqlQuery .= ' ORDER BY p.date DESC';
        
        if($limit>0){
            $sqlQuery .= ' LIMIT '.$start.','.$limit;
        }
        $retour = array();
        $results = bdd_sql::doSql($sqlQuery,true,true);
        if($results['count']>0){
            foreach ($results['results'] as $data){
                $annonce = new modules_immobilier_annonce($data['id']);
                $retour[] = $annonce;
            }
        }
        return $retour;
    }
    /**
     * renvoi le nombre total d'annonces
     * @param boolean $public default false, si true -> uniquement les biens en ligne
     * @param boolean $dispo default false, si true -> uniquement les biens non vendus
     * @return int
     */
    public static function getNombre($public=false,$dispo=false){
        $sqlQuery = 'SELECT COUNT(a.publication_id) AS nombre FROM '.PWE::getPrefixBdd().'annonce_immobiliere AS a';
        if($dispo||$public){
            if($public){
                $sqlQuery .= ' LEFT JOIN '.self::getTable().' AS p on p.id=a.publication_id';
            }
            $sqlQuery .= ' WHERE';
            if($public){
                $sqlQuery .= ' p.statut_id=2';
                if($dispo){
                    $sqlQuery .= ' AND a.statut_vente=0';
                }
            }else{
                $sqlQuery .= ' a.statut_vente=0';
            }
        }
        
        
        $result = bdd_sql::doSql($sqlQuery);
        $nombre = 0;
        if($result['count']>0){
            $nombre = $result['results'][0]['nombre'];
        }
        
        return $nombre;
    }
    
    /**
     * renvoi la liste des types de logement
     * @return array id,nom
     */
    public static function getListeTypeLogement(){
        $sqlQuery = 'SELECT * FROM '.PWE::getPrefixBdd().'type_logement ORDER BY nom';
        $retour = array();
        $results = bdd_sql::doSql($sqlQuery,true);
        if($results['count']>0){
            foreach($results['results'] as $datas){
                $retour[$datas['id']] = array(
                    'id'=>$datas['id']
                    ,'nom'=>$datas['nom']
                );
            }
        }
        return $retour;
    }
    
    /**
     * renvoi la liste des types d'item
     * @return array id,nom
     */
    public static function getListeTypeItem(){
        $sqlQuery = 'SELECT * FROM '.PWE::getPrefixBdd().'type_item ORDER BY id';
        $retour = array();
        $results = bdd_sql::doSql($sqlQuery,true);
        if($results['count']>0){
            foreach($results['results'] as $datas){
                $retour[$datas['id']] = array(
                    'id'=>$datas['id']
                    ,'nom'=>$datas['nom']
                );
            }
        }
        return $retour;
    }
}
